#coding:utf-8

# --------------------------------------------------------------------------------
# 证件的管理
# --------------------------------------------------------------------------------
module PaperTypeService
  def self.registered(app)

    app.get "/?" do
      PaperTypeRepo.all.map(&:perfect).to_json
    end
    
    app.get "/:id" do
      param :id, Integer, required: true
      elem =  PaperTypeRepo[params[:id]]
      elem.nil? ? raise("not found paper type: #{params[:id]}") : elem.perfect.to_json
    end

    app.post "/:id/toggle" do
      param :id, Integer, required: true
      elem = PaperTypeRepo[params[:id]]
      if elem
        elem.toggle; elem.save.perfect.to_json
      end
    end
    
    app.post "/?" do
      param :name,      String,  required: true
      param :cycle,     Integer, required: true,  min: 1, max: 240             # 最少1个月，最多20年
      param :delay,     Integer, required: false, default: 0, min: 0, max: 365 # 最快当天拿件，最慢一年拿件
      param :authority, String,  required: false
      param :state,     String,  required: false, in: ["enable", "disable"]
      PaperTypeRepo.create(params.symbolize_keys).perfect.to_json
    end

    app.put "/:id/?" do
      param :id,   Integer, required: true
      param :name,      String,  required: false
      param :cycle,     Integer, required: false,  min: 1, max: 240             # 最少1个月，最多20年
      param :delay,     Integer, required: false,  min: 0, max: 365 # 最快当天拿件，最慢一年拿件
      param :authority, String,  required: false
      param :state,     String,  required: false, in: ["enable", "disable"]
      elem = PaperTypeRepo[params[:id]]
      valid_params = params.keep_if{|k,v| %w(name cycle delay authority).include?(k)}.symbolize_keys
      if elem
        new_elem = elem.update(valid_params)
        (new_elem ? new_elem.save : elem).perfect.to_json
      end
    end
  end
end
